var robname = sessionStorage.getItem("apt_AT_LastSelectedRobot");
//var OpcTopic = sessionStorage.getItem("apt_" + robname + ".OpcTopic");
var OpcTopic = sessionStorage.getItem("apt_PLC.OpcTopic");
var appname = sessionStorage.getItem("apt_appName");
var pcuNr = sessionStorage.getItem("apt_" + robname + ".PCU");

var configLoaded = false;
var tagsLoaded = false;

var configData = null;
var tagData = null;

var ROBHMICONFIG = '../Content/application/apps/' + appname + '/' + robname + '/robHmiConfig.json' + '?id=' + new Date().getTime();
var ATTAGS = '../Content/application/engineering/processSchemes/processTags.json' + '?id=' + new Date().getTime();
var AT = {};

// Load Config
$.ajax({
    dataType: "json",
    url: ROBHMICONFIG,
    async: false,
    success: function (data) {
        configLoaded = true;
        configData = data;
        console.log(configData);
        buildAtTags();
    },
    error: function (jqXHR, textStatus, errorThrown) {
        AptWriteLog("[APT Error] Could not read " + ROBHMICONFIG + ". Error: " + errorThrown + "", "error");
    }
});

// Load Tags
$.ajax({
    dataType: "json",
    url: ATTAGS,
    async: false,
    success: function (data) {
        tagsLoaded = true;
        tagData = data.Tags;
        buildAtTags();
    },
    error: function (jqXHR, textStatus, errorThrown) {
        AptWriteLog("[APT Error] Could not read " + ATTAGS + ". Error: " + errorThrown + "", "error");
    }
});


function buildAtTags() {
    if (! (configLoaded && tagsLoaded)) return;

    // Iterate through config array size and replace the placeholders with numbers
    for (var key in configData["PCU" +pcuNr+"_ArraySize"]) {
        if (configData["PCU" + pcuNr + "_ArraySize"].hasOwnProperty(key)) {
            if (!tagData.hasOwnProperty(key)) continue;
            for (var tagKey in tagData[key]) {
                if (tagData[key].hasOwnProperty(tagKey)) {
                    for (var i = 1; i <= configData["PCU" + pcuNr + "_ArraySize"][key]; i++) {
                        var newKeyName = tagKey.replace('?', i);
                        AT[newKeyName] = OpcTopic + tagData[key][tagKey].replace('?', i).replace('PCU1', 'PCU' + pcuNr);
                    }
                }
            }
        }
    }
}

function getAtTags(){
    return AT;
}

//$.getScript('../content/application/processSchemes/pipeAnimations/animationScript.js');
